import { ClassName, Events } from "@/Constants";
import { IPixelPos } from "../../Interface";
import Feature from "../Feature";
import Rect from "./Rect";

// 图片/视频
class Video extends Rect {

    domElement: HTMLVideoElement | null = null;  // 图片/视频的dom元素
    _src: string | undefined // 图片/视频的地址
    get src() { return this._src }
    set src(val) {
        this._src = val;
        if (val) this.setImg(val)
    }

    /**
     * @param src 如果是html标签就传入.src属性, 如果是base64直接传入, 
     */
    constructor(src: string, x: number = 0, y: number = 0, width: number = 100, height?: number) {   // 相对坐标
        if (encodeURIComponent(src).replace(/%../g, "x").length > 2000000) {
            throw "只支持2M一下的文件!"
        }
        super(x, y, width, height);
        this.className = ClassName.VIDEO;
        this.src = src;
        this.setImg(src, width, height)
    }

    setImg(src: string, width: number = this.size.width, height?: number) {
        if (src.endsWith(".mp4") || src.startsWith("data:video/mp4;")) {
            this.domElement = document.createElement("video") as HTMLVideoElement;
            this.domElement.loop = true;
            this.domElement.src = src;
            this.domElement.muted = true;  // 静音可以自动播放
            this.domElement.style.display = "none";
            this.domElement.play();
            // 视频加载完成事件
            if (!height) {
                this.domElement.addEventListener('loadeddata', () => {  // 重新设置video大小
                    const video = this.domElement as HTMLVideoElement;
                    height = (video.videoHeight / video.videoWidth) * width;
                    this.setSize(Feature.Gls.getRelativeLen(video.videoWidth), Feature.Gls.getRelativeLen(video.videoHeight))
                    this.dispatch(new CustomEvent(Events.LOADED, { detail: {} }))
                });
                this.domElement.onerror = () => {
                    throw new Error("视频加载错误!");
                }
            }
        } else {
            throw "参数错误!"
        }
    }

    override draw(ctx: CanvasRenderingContext2D, pointArr: IPixelPos[], lineWidth: number, lineDashArr: number[]) {
        const path = super.draw(ctx, pointArr, lineWidth, lineDashArr);
        if (this.domElement) {
            const { width, height, leftTop } = this.getBboxSize(pointArr);
            ctx.save();
            path && ctx.clip(path);   // 放在旋转前面
            this.rotateCtx(ctx, Feature.getCenterPos(pointArr));
            ctx.drawImage(this.domElement, leftTop.x, leftTop.y, width, height);
            ctx.restore();
        }
        return path;
    }
}

export default Video;